#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> 
//父进程中调用fork创建一个子进程，两个进程同时存在，同时执行
int main()
{
	pid_t pid;
	char *message;
	int n;
	int exit_code;
	printf("fork program starting!\n");
	pid = fork();//
	switch(pid)
	{
	case -1:
		perror("fork failed");	
		exit(1);
	case  0:
		message = "this is child";
		n = 5;
		exit_code = 37;
		break;
	default:
		message = "this is parent";
		n = 3;
		exit_code = 0;
		break;
	}
	for(; n > 0; n--)
	{
		puts(message);
		sleep(1);
	}
	//wait for subprocess completed
	if(pid != 0)
	{
		int stat_val;
		pid_t child_pid;

		child_pid = wait(&stat_val);	//主进程被wait挂起，stat_val为子进程中return返回值或exit退出码

		printf("child has finished: PID = %d\n",child_pid);
		if(WIFEXITED(stat_val))
		{
			printf("child exited with code %d\n",WEXITSTATUS(stat_val));

		}
		else
			printf("child terminated abnormally\n");

	}
	printf("done!\n");
	exit(exit_code);
}
